﻿#region Usings

using System;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using EFCachingProvider;
using EFCachingProvider.Caching;
using EFTracingProvider;
using Microsoft.Practices.Unity;
using Omu.Awesome.Mvc;
using XPressify.Core.Unity;
using XPressify.Data;
using XPressify.Models;

#endregion

namespace XPressify
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            routes.MapRoute("Facebook",
                            "XdReceiver",
                            new { controller = "Home", action = "XdReceiver" });

//            routes.MapRoute(
//               "Post", // Route name
//               "Post/{action}/{id}/{subjectId}/{objectId}", // URL with parameters
//               new { controller = "Post", action = "Index", id = UrlParameter.Optional, subjectId = UrlParameter.Optional, objectId = UrlParameter.Optional } // Parameter defaults
//               );

           

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Home", action = "NewsFeed", id = UrlParameter.Optional} // Parameter defaults
                );

            routes.MapRoute(
              "Source included", // Route name
              "{controller}/{action}/{id}/{subjectId}", // URL with parameters
              new { controller = "Home", action = "Index2", id = UrlParameter.Optional, subjectId = UrlParameter.Optional } // Parameter defaults
              );
        }

        public override void Init()
        {
            PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
            base.Init();
        }

        protected void Application_Start()
        {
            HtmlHelper.ClientValidationEnabled = true;
            HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

            EFCachingProviderConfiguration.RegisterProvider();
            EFTracingProviderConfiguration.RegisterProvider();
            EFTracingProviderConfiguration.LogToConsole = false;

            var memoryCache = new InMemoryCache();
            var cachingPolicy = CachingPolicy.CacheAll;
            Context.Cache["Cache"] = memoryCache;
            Context.Cache["Caching_Policy"] = cachingPolicy;

            ConfigureUnityContainer();
            //var container = InitContainer();
            //DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            ViewEngines.Engines.Add(new WebFormViewEngine());

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ModelMetadataProviders.Current = new AwesomeModelMetadataProvider();
        }

        

        private static void ConfigureUnityContainer()
        {
            var container = new UnityContainer();
            container.RegisterType<IRepository, ExtendedRepository>(new ContextLifetimeManager<IRepository>(), new InjectionConstructor());
            
            ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
        }

        private static void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                var encTicket = authCookie.Value;
                if (!String.IsNullOrEmpty(encTicket))
                {
                    var ticket = FormsAuthentication.Decrypt(encTicket);
                    var id = new UserIdentity(ticket);
                    var prin = new GenericPrincipal(id, id.Roles);
                    HttpContext.Current.User = prin;
                }
            }
        }
    }
}